<script setup>
// import CustomScript from ''

// 脚本自定义
import { reactive, ref, computed } from "vue";

import request from "@/common/utils/request";

// 左边的脚本表单
import CustomScript from "./module/CustomScript.vue";
const CustomScriptRef = ref(null);
// 左边的选择商品表单
import selectGoods from "./module/selectGoods.vue";
const SelectGoodsRef = ref(null);
// 右边的列表
import RightLIst from "../RightLIst.vue";
const RightLIstRef = ref(null);
// 下方公用的表单选项
import baseForm from "./module/baseForm.vue";
const baseFormRef = ref(null);

import utils from "@/common/utils/utils.js";

import { SendOutlined, InfoCircleOutlined } from "@ant-design/icons-vue";
import { nanoid } from "nanoid";
import { message } from "ant-design-vue";
import { CondPairNullary } from "lodash";
import { nextTick } from "vue";
import { useRouter } from "vue-router";

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)

const router = useRouter();
const state = reactive({
  // 选择商品或脚本自定义
  type: 1,
  queryData: {
    page: 1,
    pageSize: 2,
  },
  // 生成的视频列表
  videoList: [
    // {
    //     "id": 697,
    //     "video_url": "https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/shotstack/video/2/4/1725508019_197_0.mp4",
    //     "poster_url": null,
    //     "duration": 0,
    //     "type": 2,
    //     "duration_text": "00:00",
    //     "resources": [],
    //     "select": false
    // }
  ],
  // 立即生成的加载状态
  loading: false,
  // preview 接口的loading, 用于右侧组件 生成更多的节流请求
  previewLoading: false,
});

// 生成更多的条数
const moreNum= ref(1);

// 收集的参数
const params = computed(() => {
  const width = baseFormRef.value?.formState?.proportion == 1 ? 1920 : 1080;
  const height = baseFormRef.value?.formState?.proportion == 1 ? 1080 : 1920;
  return {
    // 选择的生成类型
    type: state.type,
    // 宽高比例等信息
    width,
    height,
    x_ratio_scale: width,
    y_ratio_scale: height,
    // unique_id: nanoid(),
    // 商品信息和名称
    goods_name: SelectGoodsRef.value?.formState?.goods_name,
    goods_info: SelectGoodsRef.value?.formState?.goods_info,
    proportion: baseFormRef.value?.formState?.proportion,
    // 生成视频数量
    clip_num: baseFormRef.value?.formState?.clip_num,
    // 脚本文案数组
    script_text: CustomScriptRef.value?.script_tex,
    resource_data: baseFormRef?.value?.resource_data,
  };
});

// 选择的素材时长
const videoTimeValidate = computed(() => {
  if (!params.value.resource_data) return 0;
  return (
    params.value.resource_data.reduce((pre, cur) => {
      return pre + cur.material_duration;
    }, 0) / 1000
  );
});

// 校验方法
const validateTest = computed(() => {
  if (params.value.type != 0 && params.value.type != 1) {
    return {
      isOk: false,
      msg: "请选择生成类型",
    };
  } else if (params.value.proportion != 0 && params.value.proportion != 1) {
    return {
      isOk: false,
      msg: "请选择生成视频比例",
    };
  } else if (
    params.value.type == 0 &&
    !(params.value.goods_info.length && params.value.goods_name)
  ) {
    return {
      isOk: false,
      msg: "请填写商品信息",
    };
  } else if (params.value.type == 1 && !params.value.script_text.length) {
    return {
      isOk: false,
      msg: "请输入脚本",
    };
  } else if (!params.value.resource_data.length) {
    return {
      isOk: false,
      msg: "至少需要一个视频素材",
    };
  } else if (videoTimeValidate.value < 15) {
    return {
      isOk: false,
      msg: "视频总时长小于15秒",
    };
  } else if (videoTimeValidate.value > 600) {
    return {
      isOk: false,
      msg: "视频总时长大于600秒",
    };
  } else if ( typeof params.value.clip_num != "number" || params.value.clip_num < 1 || params.value.clip_num > 100 ) {
    return {
      isOk: false,
      msg: "视频生成数量在1~100之间",
    };
  } else {
    return {
      isOk: true,
      msg: "",
    };
  }
});

// 勾选的视频
const selectList = computed(() => {
  return state.videoList.filter((ele) => ele?.select);
});
// 剪辑id
const numId = ref(0);
/**
 * 重新创建 或者生成更多
 * @param {creat=重新创建} type
 */
const is_type = ref('creat');

const submitCreat = async (type) => {
  if (!validateTest.value.isOk) return;
  // 重新创建
  if (type == "creat" || type == 'resetCreat') {
    is_type.value = "creat";
    numId.value = 0;
  } else {
    // 生成更多
    is_type.value = "";
  }

  // 初始化 已用户输入为准, 生成更多 则增加 2
  const number = is_type.value == "creat" ? params.value.clip_num : moreNum.value;

  try {
        const res = await utils.oneclickPreviewNum({ number })
        // 查询积分, 积分不足则走不到这一步
        // 获取积分消耗提示内容
        const content = utils.useText(res)
        try {
          // 确认消耗
          await utils.kd({ content, res })
        } catch (error) {
          return
        }
      } catch (error) {
        // 打开充值, 接着打开点数购买
        vipVisible.value = true
    reject(error)
        // 积分不足, 关闭 生成更多弹窗
        sub_visible.value = false
        return
  }
      
    // 确定生成关闭 生成更多弹窗
  sub_visible.value = false

  // 如果是 重新生成, 在用户确定消耗之后 清空所有已生成的数据
  if (type == 'resetCreat') {    
    state.videoList = [];
    state.queryData.page = 1;
    RightLIstRef.value.resetSubmitData();
  }
  
    // 确认消耗 开始创建
    is_Save()
};

// 确认生成
const is_Save = async () => {
  state.previewLoading = true;
  state.loading = true;
  const paramsData = JSON.parse(JSON.stringify(params.value));

  // 重新创建
  if (is_type.value == "creat") {
    // 添加唯一id
    paramsData.unique_id = nanoid();
    paramsData.id = 0;
    // pagesize 为 用户填写的数量
    state.queryData.pageSize = params.value.clip_num
  } else {
    // 合并已有的id和唯一id
    // pagesize 为 用户希望添加的数量
    state.queryData.pageSize += moreNum.value;
    Object.assign(paramsData, queryId.value);
  }

  console.log(paramsData,'最终提交的参数');
  
  try {
    const res = await request.post(
      "/work_ai",
      "/user/shotstack/oneclick/preview",
      paramsData
    );
    if (res.result) {
      state.previewLoading = false;
      numId.value = res.result.id;
      getList({
        id: res.result.id,
        unique_id: paramsData.unique_id,
      });
    } else {
      throw new Error(res.msg || "生成失败!");
    }
  } catch (error) {
    message.warning(error.message);
    state.loading = false;
    state.previewLoading = false;
  }
};

const timerId = ref("");
// 项目id信息
const queryId = ref({});
// 轮询获取列表
const getList = async (data) => {
  timerId.value && clearTimeout(timerId.value);
  queryId.value = data;
  const params = {
    ...state.queryData,
    ...data,
  };
  try {
    const res = await request.get(
      "/work_ai",
      `/user/shotstack/preview/list`,
      params
    );
    console.log(res, "列表轮询结果");
    if (res?.code && res.code != 1000)
      throw new Error(res.msg || "获取列表失败");
    // if (!res.result.data.length < state.queryData.pageSize) {
    if (!res.result.all_done) {
      timerId.value = setTimeout(() => {
        getList(data);
      }, 2500);
      if (res.result.data.length) {
        // 初始化勾选逻辑
        const list = setList(res.result.data);
        state.videoList = list;
      }
      return;
    }

    state.videoList = setList(res.result.data);
    // 反向同步 pagesize 和 已加载视频的数量
    state.queryData.pageSize = res.result.data.length;
    nextTick(() => {
      state.loading = false;
    });
  } catch (error) {
    message.error(error.message);
    state.loading = false;
  }
};

const setList = (list) => {
  list.forEach((item) => {
    // 有勾选的数据, 判断是否要初始化数据
    if (selectList.value.length) {
      const index = selectList.value.findIndex((i) => i.id == item.id);
      if (index != -1) {
        item.select = selectList.value[index].select;
      } else {
        item.select = false;
      }
    } else {
      item.select = false;
    }
  });
  return list;
};

// 切换某项勾选
const selectChange = (id) => {
  const index = state.videoList.findIndex((ele) => ele.id == id);
  index != -1 &&
    (state.videoList[index].select = !state.videoList[index].select);
};

// 全选或反选
const selectAll = (val) => {
  state.videoList.forEach((item) => {
    item.select = val;
  });
};

// 生成更多
const addMore = () => {
  if(state.loading) return message.warning("正在生成中, 请稍后...")
  sub_visible.value = true
  return
  if (state.queryData.pageSize + 2 > 100)
    return message.warning("最多只能生成20个");
  // state.queryData.pageSize += 2;
  submitCreat("addMore");
};

// 重新生成
const resetConfirm = () => {
  
  
  submitCreat("resetCreat");
};

const sub_visible = ref(false);
// 我再想想
const closeFn = () => {
  sub_visible.value = false;
};

// 生成更多 最大数量
const more_Max = computed(() => {
  const max = 100 - state.videoList.length
   return max < 1 ? 1 : max
})

// 继续生成
const submitCreatMore = () => {
  // 如果已经到达 上限 100 个, 不允许继续生成
  if (moreNum.value > more_Max.value) {
    return message.warning("最多只能生成100个视频!")
  }
  submitCreat('addMore')
}

</script>

<template>
  <div class="Ecommerce">
    <div class="left_content">
      <!-- 头部固定的标题部分 -->
      <!-- <div class="sticky_title"  v-if="false">
                <div class="sticky_title_left" >
                    <h2>通用电商</h2>
                </div>

                <div class="sticky_title_right">
                    <a-radio-group v-model:value="state.type">
                        <a-radio-button :value="0">选择商品</a-radio-button>
                        <a-radio-button :value="1">脚本自定义</a-radio-button>
                    </a-radio-group>
                </div>
            </div> -->

      <!-- 左侧主要内容 -->
      <div class="left_content_box">
        <!-- 选择商品 -->
        <div v-show="state.type == 0">
          <selectGoods ref="SelectGoodsRef"></selectGoods>
        </div>

        <!-- 脚本自定义 -->
        <div v-show="state.type == 1">
          <CustomScript v-show="state.type == 1" ref="CustomScriptRef"></CustomScript>
        </div>

        <!-- 下方的基础表单 -->
        <baseForm ref="baseFormRef"></baseForm>
      </div>
      <div class="submit_btn_box">
        <!-- 判断是否校验通过 -->
        <template v-if="!validateTest.isOk">
          <a-tooltip placement="topLeft">
            <template #title>
              <span>{{ validateTest.msg }}</span>
            </template>
            <a-button disabled type="primary">
              <SendOutlined></SendOutlined>
              立即生成
            </a-button>
          </a-tooltip>
        </template>
        <template v-else>
          <template v-if="state.videoList.length">
            <a-popconfirm ok-text="确认" cancel-text="取消" @confirm="resetConfirm">
              <template #title>
                <div style="width: 288px">
                  <span style="color: #232425; font-weight: 700; font-size: 15px">是否重新生成</span>
                  <p style="color: #64666b; margin: 0; margin-top: 5px">
                    点击确认后将清空右侧信息，确定点击生成视频吗？
                  </p>
                </div>
              </template>

              <a-button type="primary" :loading="state.loading">
                <SendOutlined></SendOutlined>
                立即生成
              </a-button>
            </a-popconfirm>
          </template>

          <template v-else>
            <a-button type="primary" @click="submitCreat('creat')" :loading="state.loading">
              <SendOutlined></SendOutlined>
              立即生成
            </a-button>
          </template>
        </template>
      </div>
    </div>
    <!--
            右侧
             -->
    <div class="right_content">
      <!-- :listArr="state.videoList"  -->
      <RightLIst ref="RightLIstRef" :listArr="state.videoList" :queryData="state.queryData" :loading="state.loading"
        :previewLoading="state.previewLoading" :queryId="queryId" @selectChange="selectChange" @selectAll="selectAll"
        @addMore="addMore">
      </RightLIst>
    </div>
  </div>

  <!-- 充值弹窗 -->
  <vipModal ref="vipModalRef" :visible="vipVisible" @close="vipVisible = false"></vipModal>

  <!-- 生成更多弹窗 -->
   <!-- sub_visible -->
  <a-modal v-model:visible="sub_visible" title="合成视频">
    <div class="green">
      <div class="green-icon">
        <info-circle-outlined />
      </div>
      <div class="green-text">
        合成视频会有失败的情况,若失败则会返回对应剪辑条数
      </div>
    </div>

    <div class="kou_text">
      本次计划生成
      <div class="kou_btn">
        <a-input-number :min="1" :max="more_Max"  v-model:value="moreNum" :bordered="false" style="width: 60px;"></a-input-number >
      </div>
      个视频
      <!-- 条剪辑条数 -->
      <!-- <div v-if="usable == 0" style="margin-left: 5px; display: flex; align-items: center">
        当前{{unit_name}}不足,
        <a-button type="link" @click="goTopup" style="padding: 0; line-height: 1">点击前往充值</a-button>
      </div> -->
    </div>

    <template #footer>
      <div class="custom-footer">
        <a-button style="border-radius: 5px" @click="closeFn">取消</a-button>
        <a-button style="border-radius: 5px" type="primary" @click="submitCreatMore">确认生成</a-button>
      </div>
    </template>
  </a-modal>

</template>

<style lang="less" scoped>
@pd: 20px;

.Ecommerce {
  height: 100%;
  width: 100%;
  display: flex;
  gap: 0 20px;

  .left_content {
    background: #fff;
    border-radius: 10px;
    position: relative;
    width: 580px;
    padding: 0 @pd;
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding-top: 20px;

    .left_content_box {
      flex: 1;
      position: relative;
      overflow-y: auto;

      &::-webkit-scrollbar {
        width: 8px;
        /* 滚动条的宽度 */
        height: 10px;
        display: none;
      }

      &::-webkit-scrollbar-thumb {
        /* 滑块的背景颜色 */
        background: #a8a8a8;
        /* 滑块的圆角 */
        border-radius: 10px;
      }
    }

    .submit_btn_box {
      background-color: #fff;
      padding: 15px;
      transform: translateX(-20px);
      width: calc(100% + 40px);
      box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.1);
    }

    .sticky_title {
      width: 100%;
      // height: 50px;
      padding: 10px 0;
      padding-top: 15px;
      margin-bottom: @pd;
      border-bottom: 1px solid #ccc;
      // position: sticky;
      background: #fff;
      // top: 0;
      // left: 0px;
      z-index: 20;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .sticky_title_left {
        display: flex;
        align-items: center;
        gap: 15px;

        h2 {
          font-weight: 600;
        }
      }
    }
  }

  .right_content {
    flex: 1;
    background: #fff;
    border-radius: 10px;
  }
}

.green {
  padding: 15px 20px;
  display: flex;
  background-color: #e5f4ee;
  color: #5da488;
  font-size: 14px;
  border-radius: 5px;
  .green-icon {
    margin-right: 15px;
  }
}

.kou_text {
  margin-top: 10px;
  display: flex;
  align-items: center;
  .kou_btn {
    // padding: 5px 8px;
    margin: 0 5px;
    border: 1px solid #2c6cea;
    color: #2c6cea;
    border-radius: 8px;
    overflow: hidden;
  }
}
</style>
